package controllers

import (
	"fmt"
	"github.com/flaravel/quanlaolao/app/models/channel"
	"github.com/flaravel/quanlaolao/app/requests"
	"github.com/flaravel/quanlaolao/pkg/flash"
	"github.com/flaravel/quanlaolao/pkg/route"
	"github.com/flaravel/quanlaolao/pkg/types"
	"github.com/flaravel/quanlaolao/pkg/upload"
	"github.com/flaravel/quanlaolao/pkg/view"
	"net/http"
)

type ChannelController struct {
	BaseController
}

func (ch *ChannelController) Index(w http.ResponseWriter, r *http.Request) {
	channels, pagerData, err := channel.GetAll(r, 5)
	if err != nil {
		ch.ResposeForSQLError(w, err)
	} else {
		view.Render(w, view.D{
			"Channels":  channels,
			"PagerData": pagerData,
		}, "channel.index")
	}
}

func  (ch *ChannelController) Create(w http.ResponseWriter, r *http.Request)  {
	view.Render(w, view.D{}, "channel.create", "channel._form_field")
}

func  (ch *ChannelController) Store(w http.ResponseWriter, r *http.Request)  {
	_channel := channel.Channel{
		Name:  r.PostFormValue("name"),
		Sort:   types.StringToInt(r.PostFormValue("sort")),
	}
	errors := requests.ValidateChannelForm(_channel)

	file, header, err := r.FormFile("logo")
	if err == nil {
		logo, errs := upload.UploadImage(file,header,"channel")
		if errs != nil {
			errors["logo"] = []string{errs.Error()}
		}
		_channel.Logo = logo
	}
	if len(errors) == 0 {
		// 创建文章
		_channel.Create()
		if _channel.ID > 0 {
			flash.Success("渠道创建成功")
			indexURL := route.Name2URL("channel.index")
			http.Redirect(w, r, indexURL, http.StatusFound)
		} else {
			flash.Danger("渠道创建失败")
			view.Render(w, view.D{
				"Channel": _channel,
				"Errors":  errors,
			}, "channel.create", "channel._form_field")
		}
	} else {
		view.Render(w, view.D{
			"Channel": _channel,
			"Errors":  errors,
		}, "channel.create", "channel._form_field")
	}
}

func  (ch *ChannelController) Delete(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id",r)

	_channel , err := channel.Get(id)
	if err != nil {
		ch.ResposeForSQLError(w,err)
	} else {
		rowsAffected, err := _channel.Delete()
		if err != nil {
			w.WriteHeader(http.StatusInternalServerError)
			fmt.Fprint(w, "500 服务器内部错误")
		} else {
			if rowsAffected > 0 {
				flash.Success("删除成功")
				indexURL := route.Name2URL("channel.index")
				http.Redirect(w, r, indexURL, http.StatusFound)
			} else {
				w.WriteHeader(http.StatusNotFound)
				fmt.Fprint(w, "404 文章未找到")
			}
		}
	}
}

func  (ch *ChannelController) Edit(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id", r)
	_channel , err := channel.Get(id)
	if err != nil {
		ch.ResposeForSQLError(w, err)
	} else {
		view.Render(w, view.D{
			"Channel": _channel,
			"Errors":  view.D{},
		}, "channel.edit", "channel._form_field")
	}
}

func  (ch *ChannelController) Update(w http.ResponseWriter, r *http.Request)  {
	id := route.GetRouteVariable("id", r)
	_channel,err := channel.Get(id)

	if err != nil {
		ch.ResposeForSQLError(w,err)
	} else {
		var errors map[string][]string


		_channel.Name = r.PostFormValue("name")
		_channel.Sort = types.StringToInt(r.PostFormValue("sort"))

		errors = requests.ValidateChannelForm(_channel)

		file, header, err := r.FormFile("logo")
		if err == nil {
			logo, errs := upload.UploadImage(file,header,"channel")
			_channel.Logo = logo
			if errs != nil {
				errors["logo"] = []string{errs.Error()}
			}
		}
		if len(errors) > 0 {
			view.Render(w, view.D{
				"Channel": _channel,
				"Errors":  errors,
			}, "channel.edit", "channel._form_field")
		} else {
			rowsAffected, err := _channel.Update()
			if err != nil {
				flash.Danger("数据库错误，更改失败")
				showURL := route.Name2URL("channel.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
				return
			}

			if rowsAffected > 0 {
				flash.Success("更新成功")
				showURL := route.Name2URL("channel.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
			} else {
				flash.Danger("更新失败")
				showURL := route.Name2URL("channel.edit", "id", id)
				http.Redirect(w, r, showURL, http.StatusFound)
			}
		}
	}
}